package com.sgj.service.impl;

import com.sgj.dao.TagRepository;
import com.sgj.exception.NotFoundExcepiton;
import com.sgj.pojo.Tag;
import com.sgj.service.TagService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.List;

/**
 * @author 沈国纪
 * @date 2021/3/31 9:14
 */
@Service
public class TagServiceImpl implements TagService {

	@Autowired
	private TagRepository tagRepository;

	/**
	 * 新增标签
	 * @param tag
	 * @return
	 */
	@Transactional
	@Override
	public Tag saveTag(Tag tag) {
		return tagRepository.save(tag);
	}

	/**
	 * 根据 id 查询标签
	 * @param id
	 * @return
	 */
	@Override
	public Tag getTag(Long id) {
		return tagRepository.getOne(id);
	}

	/**
	 * 根据姓名查询标签
	 * @param name
	 * @return
	 */
	@Override
	public Tag getTagByName(String name) {
		return tagRepository.findByName(name);
	}

	/**
	 * 分页查询
	 * @param pageable
	 * @return
	 */
	@Override
	public Page<Tag> listTag(Pageable pageable) {
		return tagRepository.findAll(pageable);
	}

	/**
	 * 查询返回列表
	 * @return
	 */
	@Override
	public List<Tag> listTag() {
		return tagRepository.findAll();
	}

	/**
	 * 根据 id 数组查询标签
	 * @param ids
	 * @return
	 */
	@Override
	public List<Tag> listTag(String ids) {
		return tagRepository.findAllById(convertToList(ids));
	}

	/**
	 * 首页标签展示
	 * @param size
	 * @return
	 */
	@Override
	public List<Tag> listTagTop(Integer size) {
		Sort sort = Sort.by(Sort.Direction.DESC, "blogs.size");
		Pageable pageable = PageRequest.of(0, size, sort);
		return tagRepository.findTop(pageable);
	}

	/**
	 * 将字符串转换为集合
	 * @param ids
	 * @return
	 */
	private List<Long> convertToList(String ids) {
		List<Long> list = new ArrayList<>();
		if (StringUtils.isNotBlank(ids)) {
			String[] idarray = ids.split(",");
			for (int i = 0; i < idarray.length; i++) {
				list.add(new Long(idarray[i]));
			}
		}
		return list;
	}

	/**
	 * 更新标签
	 * @param id
	 * @param tag
	 * @return
	 */
	@Transactional
	@Override
	public Tag updateTag(Long id, Tag tag) {
		Tag t = tagRepository.getOne(id);
		if (t == null) {
			throw new NotFoundExcepiton("不存在该标签");
		}
		BeanUtils.copyProperties(tag, t);
		return tagRepository.save(t);
	}

	/**
	 * 删除标签
	 * @param id
	 */
	@Transactional
	@Override
	public void deleteTag(Long id) {
		tagRepository.deleteById(id);
	}
}